/* Copyright Florian Schweitzer
 * File created 04.12.2012
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */
package org.openuat.android;

import org.openuat.android.service.OpenUATService;
import org.openuat.android.service.interfaces.IPreferencesCallback;

import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

/**
 * A preference activity which provides to select
 * one of the available connection types and
 * one of the available authentication methods
 * @author Florian Schweitzer
 *
 */
public class OpenUATPreferencesActivity extends PreferenceActivity {
	
	/**
	 * The local shared preferences of the phone
	 */
	private SharedPreferences sharedPrefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(OpenUATService.context);
		boolean defaultSettingsEnable = sharedPrefs.getBoolean("defaultSettingsEnable", false);
		
		if (defaultSettingsEnable) {
			finish();
		} else {
			getFragmentManager().beginTransaction().replace(android.R.id.content, new OpenUATPreferencesFragment()).commit();	
		}
	}
	
	/**
	 * Fragment for the OpenUAT Preferences
	 * @author Florian Schweitzer
	 */
	public static class OpenUATPreferencesFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 0, 0, "Continue");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			finish();
		}
		return false;
	}
	
	@Override
	public void onDestroy() {		
		String connType = sharedPrefs.getString("conntypeList","-1").toUpperCase();
		String authType = sharedPrefs.getString("authtypeList","-1").toUpperCase();
		
		//Notify all registered callbacks with the preferences information
		try {
			for (IPreferencesCallback callback : OpenUATService.prefCallbackTable.values()) {
				callback.onPreferencesFinished(connType, authType);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
		super.onDestroy();
	}
}